package cn.edw.swu.bc.todolist

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log

class DBUserHelper(
    context: Context?,
    name: String?,
    version: Int
) : SQLiteOpenHelper(context, name, null, version) {
    companion object {
        val NO_USER = 100
        val WRONG_PASSWORD = 101
        val LOGIN_SUCCESSFUL = 200
    }

    val TAG = "@@userhelper"
    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(
            "CREATE TABLE ${User.TABLE} (\n" +
                    "\t${User.UID} integer PRIMARY KEY autoincrement,\n" +
                    "\t${User.USERNAME} text unique,\n" +
                    "\t${User.PASSWORD} text)"
        )
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        TODO("Not yet implemented")
    }

    @SuppressLint("Range")
    fun login(username: String, password: String): Int {
        val db = this.readableDatabase
        val cursor = db.query(
            User.TABLE, arrayOf(User.PASSWORD), User.USERNAME + "=?",
            arrayOf(username), null, null,
            null
        )

        if (cursor.count<=0)
            return NO_USER
        cursor.moveToFirst()
        val rightPassword=cursor.getString(cursor.getColumnIndex(User.PASSWORD))
        if (rightPassword == password) {
            Log.d(TAG, "验证正确")
            return LOGIN_SUCCESSFUL
        }
        return WRONG_PASSWORD
    }

    fun register(username: String, password: String): Int {
        val db = this.readableDatabase
        val value = ContentValues().apply {
            put(User.USERNAME, username)
            put(User.PASSWORD, password)
        }
        val id = db.insert(User.TABLE, null, value).toInt()
        Log.d(TAG, id.toString())
        return id
    }
}